<script setup>
import {ElMessage, ElMessageBox} from "element-plus";
import Member from '../../pojo/Member.js'
import {ref, computed, onBeforeMount} from 'vue'
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import {addMemberApi, deleteMemberApi, getMemberListApi, updateMemberApi} from "../../apis/memberApi.js";
import axios from 'axios';

onBeforeMount(async () => {
  const resp = await getMemberListApi()
  console.log(resp)
  if (resp.data.code !== 200) {
    ElMessage.error('获取数据失败')
    return
  } else {
    if (resp.data.data && resp.data.data.length > 0) {
      tableData.value = resp.data.data.map(item => new Member(
          item.id,
          item.name,
          item.classify,
          item.grade,
          item.avatar,
          item.researchInterest,
          item.currentStatus,
          item.phone,
          item.email,
          item.thesis,
          item.project,
          item.contest,
          item.reward
      ))
    } else {
      ElMessage.info('暂无成员数据')
      tableData.value = []
    }
  }
  console.log(tableData.value)
})

// 响应式数据
const tableData = ref([])
const searchText = ref('')
const dialogVisible = ref(false)
const formData = ref(new Member())
const isEdit = ref(false)
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogImageVisible = ref(false)

// 根据搜索文本过滤成员数据
let filteredTableData = computed(() => {
  if (!searchText.value) {
    return tableData.value
  }
  return tableData.value.filter(item =>
      item.name.includes(searchText.value) ||
      item.classify.includes(searchText.value) ||
      item.grade.includes(searchText.value) ||
      item.researchInterest?.includes(searchText.value) ||
      item.currentStatus?.includes(searchText.value)
  )
})

// 表单验证规则
const rules = {
  name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
  classify: [{required: true, message: '请输入分类', trigger: 'blur'}],
  grade: [{required: true, message: '请输入年级', trigger: 'blur'}],
}

// 头像上传相关方法
const customUpload = async (option) => {
  const {file} = option;
  const newName = `custom-${Date.now()}.${file.name.split(".").pop()}`;
  const newFile = new File([file], newName, {type: file.type});

  const uploadFormData = new FormData();
  uploadFormData.append("file", newFile);
  uploadFormData.append("token", "9da11413b658494f9f6b0be149f09b9f");

  try {
    const res = await axios.post("https://api.superbed.cn/upload", uploadFormData, {
      headers: {"Content-Type": "multipart/form-data"}
    });
    formData.value.avatar = res?.data?.url;
    ElMessage.success('头像上传成功');
  } catch (error) {
    ElMessage.error('头像上传失败');
  }
};

const handleExceed = () => {
  ElMessage.warning('最多只能上传一张头像');
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogImageVisible.value = true;
};

const handleRemove = () => {
  formData.value.avatar = '';
  fileList.value = [];
};

// 打开新增对话框
const openDialog = () => {
  formData.value = new Member()
  isEdit.value = false
  fileList.value = []
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  formData.value = {...row}
  isEdit.value = true
  // 如果有头像，设置文件列表
  if (row.avatar) {
    fileList.value = [{
      name: 'avatar',
      url: row.avatar
    }]
  } else {
    fileList.value = []
  }
  dialogVisible.value = true
}

// 处理删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该成员？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    console.log(index)
    console.log(tableData.value[index].id)
    const resp = await deleteMemberApi(tableData.value[index].id)
    console.log(resp)
    if (resp.data.code !== 200) {
      ElMessage.error('删除失败')
      return
    } else {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

// 提交表单
const confirmForm = async () => {
  if (isEdit.value) {
    const index = tableData.value.findIndex(item => item.id === formData.value.id)
    console.log(index)
    const resp = await updateMemberApi(formData.value)
    console.log(resp)
    if (resp.data.code !== 200) {
      ElMessage.error('修改失败')
      return
    } else {
      tableData.value[index] = formData.value
      ElMessage.success('修改成功')
    }
  } else {
    console.log(formData.value)
    const resp = await addMemberApi(formData.value)
    console.log(resp)
    if (resp.data.code !== 200) {
      ElMessage.error('新增失败')
      return
    } else {
      tableData.value.push(formData.value)
      ElMessage.success('新增成功')
    }
  }
  dialogVisible.value = false
}
</script>

<template>
  <div class="container">
    <!-- 搜索和新增区域 -->
    <div class="operation-header">
      <el-input
          v-model="searchText"
          placeholder="请输入关键词搜索"
          style="width: 300px"
          clearable
      >
        <template #prefix>
          <el-icon>
            <search/>
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="openDialog">
        <el-icon>
          <plus/>
        </el-icon>
        新增成员
      </el-button>
    </div>

    <!-- 成员表格 -->
    <el-table
        :data="filteredTableData"
        border
        style="width: 100%"
        height="calc(100vh - 180px)"
        :show-overflow-tooltip="true"
    >
      <el-table-column prop="avatar" label="头像" width="80" align="center">
        <template #default="{ row }">
          <el-avatar v-if="row.avatar" :src="row.avatar" :size="40" />
          <el-avatar v-else :size="40">{{ row.name?.charAt(0) }}</el-avatar>
        </template>
      </el-table-column>
      
      <el-table-column prop="name" label="姓名" width="100" />
      
      <el-table-column prop="classify" label="分类" width="120" />
      
      <el-table-column prop="grade" label="年级" width="100" />
      
      <el-table-column prop="researchInterest" label="研究方向" width="150" show-overflow-tooltip />
      
      <el-table-column prop="currentStatus" label="现在状态" width="120" />
      
      <el-table-column prop="phone" label="手机号" width="130" />
      
      <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
      
      <el-table-column prop="thesis" label="论文" width="200" show-overflow-tooltip />
      
      <el-table-column prop="project" label="项目" width="200" show-overflow-tooltip />
      
      <el-table-column prop="contest" label="竞赛" width="200" show-overflow-tooltip />
      
      <el-table-column prop="reward" label="奖励" width="200" show-overflow-tooltip />

      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon>
              <edit/>
            </el-icon>
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon>
              <delete/>
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑成员' : '新增成员'"
        width="600px"
    >
      <el-form :model="formData" :rules="rules" label-width="100px">
        <!-- 隐藏的ID字段，编辑时需要 -->
        <el-form-item v-if="isEdit" style="display: none;">
          <el-input v-model="formData.id" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="分类" prop="classify">
          <el-input v-model="formData.classify" placeholder="请输入分类"/>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="formData.grade" placeholder="请输入年级"/>
        </el-form-item>
        <!-- 上传头像 -->
        <el-form-item label="上传头像" prop="avatar" class="custom-form-item">
          <el-upload
              v-model:file-list="fileList"
              action="https://api.superbed.cn/upload"
              list-type="picture-card"
              :limit="1"
              :http-request="customUpload"
              :on-exceed="handleExceed"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogImageVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image"/>
          </el-dialog>
        </el-form-item>
        <el-form-item label="研究方向" prop="researchInterest">
          <el-input v-model="formData.researchInterest" placeholder="请输入研究方向"/>
        </el-form-item>
        <el-form-item label="现在状态" prop="currentStatus">
          <el-input v-model="formData.currentStatus" placeholder="请输入现在状态"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="论文" prop="thesis">
          <el-input
              v-model="formData.thesis"
              type="textarea"
              :rows="3"
              placeholder="请输入论文信息"
          />
        </el-form-item>
        <el-form-item label="项目" prop="project">
          <el-input
              v-model="formData.project"
              type="textarea"
              :rows="3"
              placeholder="请输入项目信息"
          />
        </el-form-item>
        <el-form-item label="竞赛" prop="contest">
          <el-input
              v-model="formData.contest"
              type="textarea"
              :rows="3"
              placeholder="请输入竞赛信息"
          />
        </el-form-item>
        <el-form-item label="奖励" prop="reward">
          <el-input
              v-model="formData.reward"
              type="textarea"
              :rows="3"
              placeholder="请输入奖励信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 调整行高 */
:deep(.el-table .el-table__row) {
  height: 50px;
}

/* 容器样式 */
.container {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 操作区域样式 */
.operation-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 15px;
}

/* 表单项样式 */
.el-form-item {
  margin-bottom: 22px;
}

/* 头像上传样式 */
.custom-form-item :deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}

.custom-form-item :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}
</style>